//
//  UIButton+GetCode.m
//  LogisticsProduct
//
//  Created by 孟学浩 on 2017/3/9.
//  Copyright © 2017年 com.puyiwang.logistics. All rights reserved.
//

#import "UIButton+GetCode.h"

static const void *flagKey = &flagKey;
static const void *preTitleKey = &preTitleKey;
static const void *preColorKey = &preColorKey;

@implementation UIButton (GetCode)

- (void)start{
    self.preColor = self.backgroundColor;
    self.preTitle = self.titleLabel.text;
    
    NSLog(@"%@",self.preTitle);
    self.enabled = NO;
    self.flag = @60;
    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(secondEvent:) userInfo:nil repeats:YES];
}

- (void)secondEvent:(NSTimer *)timer{
    if ([self.flag isEqualToNumber:@-1]) {
        [self setTitle:self.preTitle forState:UIControlStateNormal];
        self.backgroundColor = self.preColor;
        self.enabled = YES;
        [timer invalidate];
        return;
    }
    [self setTitle:[NSString stringWithFormat:@"%@s",self.flag] forState:UIControlStateNormal];
    self.flag = @(self.flag.intValue-1);
    
}

- (NSNumber *)flag{
    return objc_getAssociatedObject(self, flagKey);
}

- (void)setFlag:(NSNumber *)flag{
    objc_setAssociatedObject(self, flagKey, flag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)preTitle{
    return objc_getAssociatedObject(self, preTitleKey);
}

- (void)setPreTitle:(NSString *)preTitle{
    objc_setAssociatedObject(self, preTitleKey, preTitle, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)preColor{
    return objc_getAssociatedObject(self, preColorKey);
}

- (void)setPreColor:(NSString *)preColor{
    objc_setAssociatedObject(self, preColorKey, preColor, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end
